package org.jeecg.modules.bigscreen.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.apartment.service.ILwgyBaseApartmentService;
import org.jeecg.modules.bigscreen.entity.WaterJmReportDailyDate;
import org.jeecg.modules.bigscreen.mapper.WaterJmReportMapper;
import org.jeecg.modules.water.entity.LwgyJointWaterConfiguration;
import org.jeecg.modules.water.service.ILwgyJointWaterConfigurationService;
import org.jeecg.modules.water.service.ILwgyJointWaterDailyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 報表數據
 * @Author: SN
 * @Date: 2021-05-18
 * @Version: V1.0
 */
@Service
@Slf4j
public class WaterJmReportService {

    @Autowired
    private ILwgyJointWaterConfigurationService lwgyJointWaterConfigurationService;
    @Autowired
    private WaterJmReportMapper waterJmReportMapper;
    @Autowired
    private ILwgyBaseApartmentService lwgyBaseApartmentService;
    @Autowired
    private ILwgyJointWaterDailyService lwgyJointWaterDailyService;


    public JsonArray  queryNBChart( ) {
        QueryWrapper<LwgyJointWaterConfiguration> queryWrapper = new QueryWrapper();
        queryWrapper.eq("device_type","0");
        List<LwgyJointWaterConfiguration> list = lwgyJointWaterConfigurationService.list(queryWrapper);

        //电池异常
        List<LwgyJointWaterConfiguration> batteryList = list.stream()
                .filter(data -> !"0".equals(data.getBatteryStatus()) ).collect(Collectors.toList());

        //信号异常（信号小于10）
        List<LwgyJointWaterConfiguration> signalList = list.stream()
                .filter(data -> oConvertUtils.isNotEmpty(data.getSignalstrength())
                        &&Integer.parseInt(data.getSignalstrength()) <10 ).collect(Collectors.toList());

        String allCount = String.valueOf(list.size());
        String batteryCount = String.valueOf(batteryList.size());
        String signalCount = String.valueOf(signalList.size());

        JsonObject data1 = new JsonObject();
        data1.addProperty("name", "总表数量");
        data1.addProperty("value", allCount);

        JsonObject data2 = new JsonObject();
        data2.addProperty("name", "电池异常");
        data2.addProperty("value", batteryCount);

        JsonObject data3 = new JsonObject();
        data3.addProperty("name", "信号异常");
        data3.addProperty("value", signalCount);


        JsonArray dataArray = new JsonArray();
        dataArray.add(data1);
        dataArray.add(data2);
        dataArray.add(data3);
        return dataArray;
    }


    public JsonArray  queryLoraChart( ) {
        QueryWrapper<LwgyJointWaterConfiguration> queryWrapper = new QueryWrapper();
        queryWrapper.eq("device_type","1");
        List<LwgyJointWaterConfiguration> list = lwgyJointWaterConfigurationService.list(queryWrapper);
        //电池异常
        List<LwgyJointWaterConfiguration> batteryList = list.stream()
                .filter(data -> !"0".equals(data.getBatteryStatus()) ).collect(Collectors.toList());
        //信号异常（信号小于10）
        List<LwgyJointWaterConfiguration> signalList = list.stream()
                .filter(data ->oConvertUtils.isNotEmpty(data.getSignalstrength()) &&
                        Integer.parseInt(data.getSignalstrength()) <10 ).collect(Collectors.toList());
        String allCount = String.valueOf(list.size());
        String batteryCount = String.valueOf(batteryList.size());
        String signalCount = String.valueOf(signalList.size());
        JsonObject data1 = new JsonObject();
        data1.addProperty("name", "总表数量");
        data1.addProperty("value", allCount);

        JsonObject data2 = new JsonObject();
        data2.addProperty("name", "电池异常");
        data2.addProperty("value", batteryCount);

        JsonObject data3 = new JsonObject();
        data3.addProperty("name", "信号异常");
        data3.addProperty("value", signalCount);


        JsonArray dataArray = new JsonArray();
        dataArray.add(data1);
        dataArray.add(data2);
        dataArray.add(data3);
        return dataArray;
    }


    public  List<Map<String,String>>  queryCampusWaterData( ) {
        List<Map<String,String>> list = waterJmReportMapper.queryCampusWaterData();
        return list;
    }

    public  List<Map<String,String>>  queryBuildingWaterData( ) {
        List<Map<String,String>> list = waterJmReportMapper.queryBuildingWaterData();
        return list;
    }

    public  JsonArray  queryBuildingWaterChart( ) {
        List<Map<String,String>> list = waterJmReportMapper.queryBuildingWaterData();
        System.out.println("list:"+list);


        JsonArray dataArray = new JsonArray();
    /*    for (Map<String, String> map : list) {

            JsonObject data = new JsonObject();
            BigDecimal nbBigDecimal = new BigDecimal(String.valueOf(map.get("nb")));
            String nbString = nbBigDecimal.toString(); // 将 BigDecimal 转换为 String


            data.addProperty("name", "nb表数");
            data.addProperty("value",nbString);
            data.addProperty("type", map.get("xq")+map.get("build"));
            dataArray.add(data);

            JsonObject data1 = new JsonObject();

            BigDecimal loraBigDecimal = new BigDecimal(String.valueOf(map.get("lora")));
            String loraString = loraBigDecimal.toString(); // 将 BigDecimal 转换为 String

            data1.addProperty("name", "lora表数");
            data1.addProperty("value",loraString);
            data1.addProperty("type", map.get("xq")+map.get("build"));
            dataArray.add(data1);

            JsonObject data2 = new JsonObject();


            BigDecimal signslBigDecimal = new BigDecimal(String.valueOf(map.get("signsl")));
            String signString = signslBigDecimal.toString(); // 将 BigDecimal 转换为 String

            data2.addProperty("name", "信号异常");
            data2.addProperty("value",signString);
            data2.addProperty("type", map.get("xq")+map.get("build"));
            dataArray.add(data2);

        }*/

    for(int i=0;i<list.size();i++){
        Map map = list.get(i);

        JsonObject data = new JsonObject();
        //BigDecimal nbBigDecimal = new BigDecimal(String.valueOf(map.get("nb")));
       // String nbString = nbBigDecimal.toString(); // 将 BigDecimal 转换为 String


        data.addProperty("name", map.get("xq").toString()+map.get("build").toString());
        data.addProperty("value",map.get("nb").toString());
        data.addProperty("type", "nb表数");
        dataArray.add(data);

        JsonObject data1 = new JsonObject();

        BigDecimal loraBigDecimal = new BigDecimal(String.valueOf(map.get("lora")));
        String loraString = loraBigDecimal.toString(); // 将 BigDecimal 转换为 String

        data1.addProperty("name", map.get("xq").toString()+map.get("build").toString());
        data1.addProperty("value",loraString);
        data1.addProperty("type", "lora表数");
        dataArray.add(data1);

        JsonObject data2 = new JsonObject();


        BigDecimal signslBigDecimal = new BigDecimal(String.valueOf(map.get("signsl")));
        String signString = signslBigDecimal.toString(); // 将 BigDecimal 转换为 String

        data2.addProperty("name", map.get("xq").toString()+map.get("build").toString());
        data2.addProperty("value",signString);
        data2.addProperty("type", "信号异常");
        dataArray.add(data2);
    }

     /*   JsonArray dataArray = new JsonArray();
        if(list.size()>0){
            list.stream().forEach(item -> {
                JsonObject data = new JsonObject();
                data.addProperty("name", "nb表数");
                data.addProperty("value", String.valueOf(item.get("nb")));
                data.addProperty("type", item.get("xq")+item.get("build"));
                dataArray.add(data);

                JsonObject data1 = new JsonObject();
                data1.addProperty("name", "lora表数");
                data1.addProperty("value",String.valueOf(item.get("lora")));
                data1.addProperty("type", item.get("xq")+item.get("build"));
                dataArray.add(data1);

                JsonObject data2 = new JsonObject();
                data2.addProperty("name", "信号异常");
                data2.addProperty("value", item.get("signsl"));
                data2.addProperty("type", item.get("xq")+item.get("build"));
                dataArray.add(data2);
            });*/

          /*  JsonObject data = new JsonObject();
            data.addProperty("name", "总表数量");
            data.addProperty("value", allCount);
            data.addProperty("type", allCount);
            dataArray.add(data);*/

        return dataArray;
    }


    public  List<WaterJmReportDailyDate>  queryBuildingUseWaterData() throws ParseException {

       //获取所有楼宇信息
        List<Map<String,String>> list = waterJmReportMapper.queryBuildingData();

        //最近一个月的日用水量信息，带楼宇信息
        LocalDate currentDate = LocalDate.now();
        LocalDate oneMonthAgo = currentDate.minusMonths(1);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = oneMonthAgo.format(formatter);

        List<Map<String,Object>> dailylist = waterJmReportMapper.qieryDilayAvgData(formattedDate.toString());

        List<WaterJmReportDailyDate> resultList = new ArrayList<>() ;
        Double day = 0.0;
        Double week = 0.0;
        Double month = 0.0;
        // 创建 Calendar 实例并设置为今天的日期
        Calendar calendarToday = Calendar.getInstance();
        calendarToday.set(Calendar.HOUR_OF_DAY, 0);
        calendarToday.set(Calendar.MINUTE, 0);
        calendarToday.set(Calendar.SECOND, 0);
        calendarToday.set(Calendar.MILLISECOND, 0);

        for( Map  lwgyBaseApartment : list){
            WaterJmReportDailyDate dailyDate = new WaterJmReportDailyDate();
            dailyDate.setCampusName(lwgyBaseApartment.get("campus_name").toString());
            dailyDate.setBuildingName(lwgyBaseApartment.get("building_name").toString());

            day = 0.0;
            week = 0.0;
            month = 0.0;
            if(dailylist!=null && dailylist.size()!=0){
                for(Map<String,Object> map : dailylist){

                    if(lwgyBaseApartment.get("building_id").equals(map.get("building_id"))){
                        //String value = map.get("avg_value").toString();
                        Double avgValue = (Double) map.get("avg_value");

                        month+=avgValue;
                        Date getTime = new SimpleDateFormat("yyyy-MM-dd").parse(map.get("create_time").toString()) ;
                        System.out.println("getTime:"+getTime);
                        // 创建 Calendar 实例并设置为要判断的日期
                        Calendar calendarToCheck = Calendar.getInstance();
                        calendarToCheck.setTime(getTime);
                        // 判断是否是今天的日期
                        boolean isToday = calendarToday.get(Calendar.YEAR) == calendarToCheck.get(Calendar.YEAR) &&
                                calendarToday.get(Calendar.MONTH) == calendarToCheck.get(Calendar.MONTH) &&
                                calendarToday.get(Calendar.DAY_OF_MONTH) == calendarToCheck.get(Calendar.DAY_OF_MONTH);

                        // 判断是否是本周
                        boolean isThisWeek = calendarToday.get(Calendar.YEAR) == calendarToCheck.get(Calendar.YEAR) &&
                                calendarToday.get(Calendar.WEEK_OF_YEAR) == calendarToCheck.get(Calendar.WEEK_OF_YEAR);

                        if(isToday){//今天的时间
                            day+=avgValue;
                        }

                        if(isThisWeek){//本周的时间
                            week+=avgValue;
                        }

                    }
                }
            }

            dailyDate.setDayNum(day+"");
            dailyDate.setWeekNum(week+"");
            dailyDate.setMonthNum(month+"");

            resultList.add(dailyDate);
        }


        return resultList;
    }



    public  List<WaterJmReportDailyDate>  queryBuildingDailyWaterData() throws ParseException {
        //查询今日用水量和昨日用水量

        //获取所有楼宇信息
        List<Map<String,String>> list = waterJmReportMapper.queryBuildingData();

        //最近两天的日用水量信息，带楼宇信息
        LocalDate currentDate = LocalDate.now();
        // 获取前一天的日期
        LocalDate oneDayAgo = currentDate.minusDays(1);
        // 获取前两天的日期
        LocalDate twoDaysAgo = currentDate.minusDays(2);

        System.out.println("当前日期：" + currentDate);
        System.out.println("前一天的日期：" + oneDayAgo);
        System.out.println("前两天的日期：" + twoDaysAgo);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate1 = oneDayAgo.format(formatter);
        String formattedDate2 = twoDaysAgo.format(formatter);

        List<Map<String,Object>> dailylist = waterJmReportMapper.qieryDilayAvgData(twoDaysAgo.toString());



        List<WaterJmReportDailyDate> resultList = new ArrayList<>() ;
        Double day = 0.0;
        Double week = 0.0;
        Double month = 0.0;
        // 创建 Calendar 实例并设置为今天的日期
        Calendar calendarToday = Calendar.getInstance();
        calendarToday.set(Calendar.HOUR_OF_DAY, 0);
        calendarToday.set(Calendar.MINUTE, 0);
        calendarToday.set(Calendar.SECOND, 0);
        calendarToday.set(Calendar.MILLISECOND, 0);

        for( Map  lwgyBaseApartment : list){
            WaterJmReportDailyDate dailyDate = new WaterJmReportDailyDate();
            dailyDate.setCampusName(lwgyBaseApartment.get("campus_name").toString());
            dailyDate.setBuildingName(lwgyBaseApartment.get("building_name").toString());

            day = 0.0;
            week = 0.0;
            month = 0.0;
            if(dailylist!=null && dailylist.size()!=0){
                for(Map<String,Object> map : dailylist){

                    if(lwgyBaseApartment.get("building_id").equals(map.get("building_id"))){
                        //String value = map.get("avg_value").toString();
                        Double avgValue = (Double) map.get("avg_value");

                        month+=avgValue;
                        Date getTime = new SimpleDateFormat("yyyy-MM-dd").parse(map.get("create_time").toString()) ;
                        System.out.println("getTime:"+getTime);
                        // 创建 Calendar 实例并设置为要判断的日期
                        Calendar calendarToCheck = Calendar.getInstance();
                        calendarToCheck.setTime(getTime);
                        // 判断是否是今天的日期
                        boolean isToday = calendarToday.get(Calendar.YEAR) == calendarToCheck.get(Calendar.YEAR) &&
                                calendarToday.get(Calendar.MONTH) == calendarToCheck.get(Calendar.MONTH) &&
                                calendarToday.get(Calendar.DAY_OF_MONTH) == calendarToCheck.get(Calendar.DAY_OF_MONTH);

                        // 判断是否是本周
                        boolean isThisWeek = calendarToday.get(Calendar.YEAR) == calendarToCheck.get(Calendar.YEAR) &&
                                calendarToday.get(Calendar.WEEK_OF_YEAR) == calendarToCheck.get(Calendar.WEEK_OF_YEAR);

                        if(isToday){//今天的时间
                            day+=avgValue;
                        }

                        if(isThisWeek){//本周的时间
                            week+=avgValue;
                        }

                    }
                }
            }

            dailyDate.setDayNum(day+"");
            dailyDate.setWeekNum(week+"");
            dailyDate.setMonthNum(month+"");

            resultList.add(dailyDate);
        }


        return resultList;
    }



    public  JsonArray  queryBuildingDailyWaterChart() throws ParseException {
        //获取所有楼宇信息
        List<Map<String,String>> list = waterJmReportMapper.queryBuildingData();

        //最近两天的日用水量信息，带楼宇信息
        LocalDate currentDate = LocalDate.now();
        // 获取前一天的日期
        LocalDate oneDayAgo = currentDate.minusDays(1);
        // 获取前两天的日期
        LocalDate twoDaysAgo = currentDate.minusDays(2);
        System.out.println("当前日期：" + currentDate);
        System.out.println("前一天的日期：" + oneDayAgo);
        System.out.println("前两天的日期：" + twoDaysAgo);

        List<Map<String,Object>> dailylist = waterJmReportMapper.qieryDilayAvgTypeData(twoDaysAgo.toString());


        JsonArray dataArray = new JsonArray();
        for(Map<String,String> map:list) {

            JsonObject data = new JsonObject();
            data.addProperty("name", map.get("campus_name").toString() + map.get("building_name").toString());
            data.addProperty("value", 0);
            data.addProperty("type", "nb表数");

            JsonObject data1 = new JsonObject();
            data1.addProperty("name", map.get("campus_name").toString() + map.get("building_name").toString());
            data1.addProperty("value", 0);
            data1.addProperty("type", "lora表数");


            for (Map<String, Object> map2 : dailylist) {

                if (map.get("building_id").equals(map2.get("building_id"))) {
                    if (map2.get("device_type").equals("0")) {
                        data.addProperty("value", map2.get("avg_value").toString());
                    }
                    if (map2.get("device_type").equals("1")) {
                        data1.addProperty("value", map2.get("avg_value").toString());
                    }
                }

                dataArray.add(data);
                dataArray.add(data1);
            }

        }
        return dataArray;
    }
}